<template>
  <edit-card title="创建训练任务" type="add" :loading="submitLoading" back-url="/admin/algo-service-manage/list" @confirm="handleConfirm">
    <div class="content-box">
      <a-anchor style="position: absolute; right: -50px" :show-ink-in-fixed="false" :offset-top="200" :target-offset="500">
        <a-anchor-link href="#addService" title="任务详情" />
        <a-anchor-link href="#addVersion" title="资源分配" />
      </a-anchor>
      <div id="addService">
        <div class="module-title">
          <span class="title">任务详情</span>
        </div>
        <div class="form-wrap">
          <a-form ref="formRef" :colon="false" :model="baseFrom" label-align="left" :rules="rules">
            <a-form-item label="任务名称" name="name">
              <a-input v-model:value="baseFrom.name" v-trim class="w-440" :maxlength="200" placeholder="请输入任务名称" />
            </a-form-item>
            <a-form-item label="任务类型" name="type">
              <a-select v-model:value="baseFrom.name" style="width: 440px" placeholder="请选择任务类型" :options="typeOptions" />
            </a-form-item>
            <a-form-item label="运行命令" name="name">
              <a-input v-model:value="baseFrom.name" v-trim class="w-440" :maxlength="200" placeholder="请输入运行命令" />
            </a-form-item>
            <a-form-item label="镜像" name="name">
              <a-input v-model:value="baseFrom.name" v-trim class="w-440" disabled :maxlength="200" placeholder="请输入镜像" />
            </a-form-item>
            <a-form-item label="框架" name="name">
              <a-input v-model:value="baseFrom.name" v-trim class="w-440" disabled :maxlength="200" placeholder="请输入框架" />
            </a-form-item>
            <a-form-item label="运行参数" name="runParameters">
              <a-space
                v-for="(param, index) in baseFrom.runParameters"
                :key="index"
                class="w-440"
                style="display: flex; gap: 12px"
                align="baseline"
              >
                <a-form-item
                  class="w-215"
                  :name="['runParameters', index, 'name']"
                  :rules="{
                    required: true,
                    message: '请输入参数'
                  }"
                >
                  <a-input v-model:value="param.name" v-trim :disabled="!param.canDelete" placeholder="请输入参数" />
                </a-form-item>
                <a-form-item
                  class="w-215"
                  :name="['runParameters', index, 'value']"
                  :rules="{
                    required: true,
                    message: '请输入值'
                  }"
                >
                  <a-input v-model:value="param.value" v-trim placeholder="请输入值" />
                </a-form-item>
                <MinusCircleOutlined v-if="param.canDelete" style="color: #cccdcf" title="删除" @click="removeParamInput(param)" />
              </a-space>
              <div v-if="showAddRunParamBtn" class="w-440">
                <a-button type="dashed" block @click="addRunParam">
                  <PlusOutlined />
                  <span style="color: rgba(17, 22, 31, 0.75)">添加</span>
                </a-button>
              </div>
            </a-form-item>
            <a-form-item label="数据集" name="dataIds">
              <div class="w-866">
                <g-select-tree-data
                  ref="selectDataBucketRef"
                  v-model:checkedIds="baseFrom.dataIds"
                  type-name="数据集"
                  :has-modal="false"
                  :get-tree-data-api="selectTreeDataApi.dataBucketTree"
                  :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
                  :get-list-data-api="selectTreeDataApi.searchBucketList"
                  :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
                  :field-names="{ children: 'children', title: 'name', key: 'id' }"
                >
                  <template #selected-tools>
                    <a-tooltip title="仅从已选数据集中抽取满足“数据处理规则”格式条件的文件">
                      <i class="iconfont icon-information-fill text-color-4 ml-8 h-22"></i>
                    </a-tooltip>
                  </template>
                </g-select-tree-data>
              </div>
            </a-form-item>
            <a-form-item label="验证集" name="validationSetRadio">
              <a-radio-group v-model:value="baseFrom.validationSetRadio" class="w-866 pt-4 pb-16">
                <a-radio value="1">随机抽取</a-radio>
                <a-radio value="2">自定义</a-radio>
              </a-radio-group>
              <a-form-item
                v-if="baseFrom.validationSetRadio === '1'"
                name="randomNum"
                :rules="{
                  required: true,
                  message: '请选择数据集'
                }"
              >
                <div class="flex gap-x-8 items-center">
                  <a-input-number v-model:value="baseFrom.randomNum" :min="1" :max="100" />
                  %
                </div>
              </a-form-item>

              <a-form-item
                v-else
                name="dataIds"
                :rules="{
                  required: true,
                  message: '请选择数据集'
                }"
              >
                <div class="w-866">
                  <g-select-tree-data
                    ref="selectDataBucketRef"
                    v-model:checkedIds="baseFrom.dataIds"
                    type-name="数据集"
                    :has-modal="false"
                    :get-tree-data-api="selectTreeDataApi.dataBucketTree"
                    :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
                    :get-list-data-api="selectTreeDataApi.searchBucketList"
                    :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
                    :field-names="{ children: 'children', title: 'name', key: 'id' }"
                  >
                    <template #selected-tools>
                      <a-tooltip title="仅从已选数据集中抽取满足“数据处理规则”格式条件的文件">
                        <i class="iconfont icon-information-fill text-color-4 ml-8 h-22"></i>
                      </a-tooltip>
                    </template>
                  </g-select-tree-data>
                </div>
              </a-form-item>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div id="addVersion">
        <div class="module-title">
          <span class="title">资源分配</span>
        </div>

        <a-form ref="resourceRef" :model="resourceForm" :colon="false" :rules="resourceRules" name="resourceForm">
          <a-form-item label="GPU" name="gpu">
            <a-select v-model:value="resourceForm.gpu" style="width: 440px" placeholder="请选择任务类型" :options="typeOptions" />
          </a-form-item>
          <a-form-item label="CPU" name="cpu">
            <a-select v-model:value="resourceForm.cpu" style="width: 440px" placeholder="请选择任务类型" :options="typeOptions" />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </edit-card>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import { dmpTaskApi, selectTreeDataApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  interface AddInputType {
    name: string
    value: any
    canDelete: boolean
    uid?: number
  }

  interface BaseForm {
    name: string
    typeId: number
    dataIds: string[]
    modelName: string
    validationSetRadio: string
    randomNum: number
    dataNames: string[]
    runParameters: AddInputType[]
  }

  const route = useRoute()
  const taskId = route.params.id as string | ''
  console.log(taskId)

  const typeOptions = ref([
    { label: '分类', value: '1' },
    { label: '回归', value: '2' },
    { label: '聚类', value: '3' },
    { label: '关联', value: '4' },
    { label: '推荐', value: '5' },
    { label: '时序', value: '6' },
    { label: '异常检测', value: '7' },
    { label: '图分析', value: '8' },
    { label: '文本分析', value: '9' },
    { label: '图像分析', value: '10' },
    { label: '音频分析', value: '11' },
    { label: '视频分析', value: '12' }
  ])

  const formRef = ref()
  const baseFrom = ref<BaseForm>({
    name: '',
    typeId: 0,
    randomNum: 0,
    dataIds: [],
    modelName: '',
    validationSetRadio: '1',
    dataNames: [],
    runParameters: []
  })

  let validateDataBucket = async (rule: Rule, value: string) => {
    if (value.length === 0) {
      return Promise.reject('请选择数据集')
    }
    return Promise.resolve()
  }

  // 验证规则
  const rules: Record<string, Rule[]> = {
    name: [
      { required: true, message: '请输入算法服务名称', trigger: 'change' },
      { validator: validateDirName() },
      { validator: validateBitLen(200), trigger: 'change' }
    ],
    dataIds: [{ required: true, trigger: 'change', validator: validateDataBucket }],
    runCommand: [{ required: true, message: '请输入运行命令' }],
    validationSetRadio: [{ required: true, message: '请选择验证集' }],
    runParameters: [{ required: true, message: '请输入运行参数' }]
  }

  /* 资源分配逻辑-------------------------------------------------------------------------- */
  let resourceForm = ref({
    cpu: 4,
    gpu: 4
  })
  let resourceRef = ref()
  const resourceRules: Record<string, Rule[]> = {
    cpu: [{ required: true, message: '请输入CPU限制' }],
    gpu: [{ required: true, message: '请输入GPU限制' }]
  }

  /**
   * 确认提交
   */
  const { loading: submitLoading, runAsync: runSubmit } = useRequest(dmpTaskApi.add)
  const handleConfirm = async () => {
    await formRef.value.validate()
    await runSubmit(baseFrom.value)
    console.log('handleConfirm')
  }

  /* -----------------------------------------------运行参数------------------------------------------------ */
  const showAddRunParamBtn = ref(true)
  /**
   * 增加运行参数
   */
  const addRunParam = () => {
    if (baseFrom.value.runParameters.length > 10) {
      return message.warning('最多只能添加十条')
    }
    baseFrom.value.runParameters.push({
      name: '',
      value: '',
      canDelete: true,
      uid: Date.now()
    })
  }
  /**
   * 删除运行参数
   */
  const removeParamInput = (param: AddInputType) => {
    baseFrom.value.runParameters = baseFrom.value.runParameters.filter(item => item.uid !== param.uid)
  }
</script>

<style lang="less" scoped>
  // input {
  //   width: 440px !important;
  // }

  :deep(.ant-form-item) {
    margin-bottom: 40px;
  }

  :deep(.ant-form-item-label > label) {
    min-width: 120px;
  }

  .content-box {
    .module-title {
      display: flex;
      align-items: center;
      padding: 0 0 56px;

      .title {
        .font20b();

        position: relative;
        color: rgba(16, 16, 20, 0.95);

        &::before {
          position: absolute;
          top: 50%;
          left: -16px;
          width: 3px;
          height: 22px;
          background: #1868e9;
          border-radius: 0 2px 2px 0;
          content: '';
          transform: translateY(-50%);
          flex: none;
          order: 0;
          align-self: stretch;
          flex-grow: 0;
        }
      }
    }

    .form-wrap {
      max-width: 824px;
    }
  }
</style>
